package com.tanhua.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.mongo.VideoScore;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
public class RecommendVideoListener {

    private MongoTemplate mongoTemplate;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "tanhua.video.queue", durable = "true"),
                    exchange = @Exchange(value = "tanhua.log.exchange", type = ExchangeTypes.TOPIC),
                    key = "log.video"
            ))
    public void video(String message) {
        System.out.println("动态消息 ="+ message);
        try {
            //解析message
            Map<String, Object> map = JSON.parseObject(message);
            Long userId = Long.valueOf(map.get("userId").toString());
            String logTime = (String) map.get("logTime");
            String type = (String) map.get("type");
            String busId = (String) map.get("busId");
            //通过视频id获取视频数据
            Video video = mongoTemplate.findById(busId, Video.class);
            //判断是否为空
            if (!StringUtils.isEmpty(video)) {
                //不为空就构造视频大数据评分 并且保存
                VideoScore vs = new VideoScore();
                vs.setDate(System.currentTimeMillis());
                vs.setUserId(userId);
                vs.setVideoId(video.getVid());
                vs.setScore(getScore(type));
                mongoTemplate.save(vs);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
    private static Double getScore(String type) {
        //0301为发小视频，0302为小视频点赞，0303为小视频取消点赞，0304为小视频评论
        Double score = 0d;
        switch (type) {
            case "0301":
                score=2d;
                break;
            case "0302":
                score=5d;
                break;
            case "0303":
                score = -5d;
                break;
            case "0304":
                score = 10d;
                break;
            default:
                break;
        }
        return score;
    }
}
